import React, { useEffect, useRef, useState } from 'react';
import { connectWebRTC, stopWebRTC } from '../services/RTCService';

const CameraCapture = ({ onStreamStatusChange, onCameraStatusChange }) => {
  const videoRef = useRef(null);
  const streamRef = useRef(null);
  const [isStreaming, setIsStreaming] = useState(false);
  const [error, setError] = useState(null);
  const [publishUrl, setPublishUrl] = useState('');
  const connectionTimerRef = useRef(null);
  const heartbeatTimerRef = useRef(null);
  const [isCameraLoading, setIsCameraLoading] = useState(false);
  const [isCameraReady, setIsCameraReady] = useState(false);
  const [reconnectCount, setReconnectCount] = useState(0);
  
  // 移除自动初始化摄像头的useEffect，改为仅在组件卸载时清理资源
  useEffect(() => {
    return () => {
      cleanupResources();
    };
  }, []);
  
  // 状态变化时通知父组件
  useEffect(() => {
    if (typeof onCameraStatusChange === 'function') {
      onCameraStatusChange(isCameraLoading);
    }
  }, [isCameraLoading, onCameraStatusChange]);
  
  // 资源清理函数
  const cleanupResources = () => {
    if (streamRef.current) {
      stopWebRTC();
      streamRef.current.getTracks().forEach(track => track.stop());
      streamRef.current = null;
    }
    
    if (connectionTimerRef.current) {
      clearTimeout(connectionTimerRef.current);
    }
    
    if (heartbeatTimerRef.current) {
      clearInterval(heartbeatTimerRef.current);
    }
  };
  
  // 初始化摄像头
  const initCamera = async () => {
    try {
      setIsCameraLoading(true);
      setError(null);
      
      const constraints = {
        audio: true,
        video: {
          width: { ideal: 1280 },
          height: { ideal: 720 },
          frameRate: { ideal: 30 }
        }
      };
      
      console.log('正在请求摄像头权限...');
      const stream = await navigator.mediaDevices.getUserMedia(constraints);
      streamRef.current = stream;
      
      if (videoRef.current) {
        console.log('设置视频源...');
        videoRef.current.srcObject = stream;
        
        // 添加加载事件监听
        videoRef.current.onloadedmetadata = () => {
          console.log('视频元数据已加载，准备播放');
          videoRef.current.play()
            .then(() => {
              console.log('视频开始播放');
              // 检测视频尺寸
              setTimeout(() => {
                console.log('视频尺寸:', {
                  width: videoRef.current.videoWidth,
                  height: videoRef.current.videoHeight,
                  displaying: window.getComputedStyle(videoRef.current).display,
                  visibility: window.getComputedStyle(videoRef.current).visibility
                });
              }, 500);
            })
            .catch(err => {
              console.error('自动播放失败:', err);
              // 添加播放按钮让用户手动触发
              setError('视频自动播放失败，请点击"关闭"按钮后再次尝试启动摄像头');
            });
        };
      }
      
      setIsCameraLoading(false);
      setIsCameraReady(true);
      console.log('摄像头已准备就绪');

      // 强制刷新视频元素
      if (videoRef.current) {
        const track = stream.getVideoTracks()[0];
        if (track) {
          // 临时禁用再启用视频轨道，强制刷新
          track.enabled = false;
          setTimeout(() => {
            track.enabled = true;
            console.log('已强制刷新视频轨道');
          }, 100);
        }
      }

      return stream;
    } catch (err) {
      console.error('初始化摄像头失败:', err);
      setError(`初始化摄像头失败: ${err.message || '未知错误'}`);
      setIsCameraLoading(false);
      setIsCameraReady(false);
      throw err;
    }
  };
  
  // 开始推流
  const startStreaming = async () => {
    try {
      // 先初始化摄像头
      const stream = await initCamera();
      
      console.log('开始WebRTC推流...');
      // 开始WebRTC推流
      try {
        const { publishUrl, sessionid } = await connectWebRTC(stream);
        
        // 再次确认视频元素状态
        console.log('视频元素当前状态:', {
          元素存在: !!videoRef.current,
          视频源: !!videoRef.current?.srcObject,
          视频宽度: videoRef.current?.videoWidth,
          视频高度: videoRef.current?.videoHeight,
          视频暂停状态: videoRef.current?.paused,
          视频就绪状态: videoRef.current?.readyState,
          视频显示样式: videoRef.current?.style.display
        });
        
        if (publishUrl) {
          setIsStreaming(true);
          setPublishUrl(publishUrl);
          onStreamStatusChange(true);
          console.log('成功开始WebRTC推流', publishUrl);
          
          // 重置重连计数
          setReconnectCount(0);
          
          // 设置心跳
          if (heartbeatTimerRef.current) {
            clearInterval(heartbeatTimerRef.current);
          }
          
          heartbeatTimerRef.current = setInterval(() => {
            console.log('WebRTC连接心跳...');
          }, 30000);
        } else {
          setError('推流URL无效，请检查SRS服务器配置');
        }
      } catch (rtcError) {
        console.error('WebRTC连接失败:', rtcError);
        
        // 尝试自动重连
        if (reconnectCount < 2) {
          console.log(`推流连接失败，正在尝试重连... (${reconnectCount + 1}/2)`);
          setError(`连接失败，正在尝试重连... (${reconnectCount + 1}/2)`);
          
          setReconnectCount(prev => prev + 1);
          
          // 延迟1秒后重试
          connectionTimerRef.current = setTimeout(async () => {
            try {
              const { publishUrl, sessionid } = await connectWebRTC(stream);
              setIsStreaming(true);
              setPublishUrl(publishUrl);
              onStreamStatusChange(true);
              setError(null);
              console.log('重连成功!', publishUrl);
            } catch (retryError) {
              console.error('重连失败:', retryError);
              setError(`重连失败: ${retryError.message || '未知错误'}`);
              // 如果重连失败，清理资源
              cleanupCamera();
              onStreamStatusChange(false);
            }
          }, 1000);
        } else {
          setError(`多次连接失败: ${rtcError.message || '未知错误'}`);
          // 如果多次重连失败，清理资源
          cleanupCamera();
          onStreamStatusChange(false);
        }
      }
    } catch (err) {
      console.error('开始推流时出错:', err);
      setError(`启动失败: ${err.message || '未知错误'}`);
      // 确保清理已创建的资源
      cleanupCamera();
      onStreamStatusChange(false);
    }
  };
  
  // 清理摄像头资源
  const cleanupCamera = () => {
    if (streamRef.current) {
      streamRef.current.getTracks().forEach(track => {
        track.stop();
        console.log(`已停止${track.kind}轨道`);
      });
      streamRef.current = null;
    }
    
    if (videoRef.current) {
      videoRef.current.srcObject = null;
      videoRef.current.load(); // 重置视频元素状态
    }
    
    setIsCameraReady(false);
  };
  
  // 处理停止推流
  const handleStopStreaming = () => {
    console.log('手动停止推流和摄像头');
    
    // 先更新本地状态
    setIsStreaming(false);
    setPublishUrl('');
    
    // 通知父组件状态变化
    onStreamStatusChange(false);
    
    // 停止WebRTC连接
    stopWebRTC().catch(err => {
      console.error('停止WebRTC失败:', err);
    });
    
    // 停止摄像头并清理资源
    cleanupCamera();
    
    // 清除所有定时器
    if (heartbeatTimerRef.current) {
      clearInterval(heartbeatTimerRef.current);
      heartbeatTimerRef.current = null;
    }
    
    if (connectionTimerRef.current) {
      clearTimeout(connectionTimerRef.current);
      connectionTimerRef.current = null;
    }
  };
  
  // 切换推流状态
  const toggleStreaming = async () => {
    console.log('点击切换推流按钮，当前状态:', { 
      isStreaming, 
      isCameraLoading, 
      isCameraReady 
    });
    
    if (isStreaming) {
      handleStopStreaming();
    } else {
      startStreaming();
    }
  };

  return (
    <div className="camera-container" style={{ width: '100%', height: '380px' }}>
      <div className="video-container" style={{ position: 'relative', width: '100%', height: 'calc(100% - 50px)', backgroundColor: '#000' }}>
        <video 
          ref={videoRef} 
          autoPlay 
          playsInline 
          muted
          style={{ 
            width: '100%', 
            height: '100%',
            objectFit: 'cover',
            backgroundColor: '#000',
            display: 'block'
          }} 
        />
        
        {isCameraLoading && (
          <div className="loading-indicator" style={{ 
            position: 'absolute', 
            top: '50%', 
            left: '50%', 
            transform: 'translate(-50%, -50%)',
            color: 'white',
            textAlign: 'center',
            zIndex: 10
          }}>
            <div>正在启动摄像头...</div>
          </div>
        )}
        
        {!isCameraReady && !isCameraLoading && (
          <div className="camera-placeholder" style={{ 
            position: 'absolute', 
            top: '50%', 
            left: '50%', 
            transform: 'translate(-50%, -50%)',
            color: 'white',
            textAlign: 'center',
            zIndex: 5
          }}>
            <div>点击"开始推流"以启动摄像头</div>
          </div>
        )}
      </div>
      
      <div style={{ 
        padding: '10px', 
        textAlign: 'center',
        backgroundColor: '#f5f5f5',
        borderTop: '1px solid #ddd'
      }}>
        <button 
          onClick={toggleStreaming}
          disabled={isCameraLoading} 
          style={{
            padding: '8px 20px',
            background: isStreaming ? '#e74c3c' : '#3498db',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: isCameraLoading ? 'not-allowed' : 'pointer',
            fontSize: '16px',
            fontWeight: 'bold'
          }}
        >
          {isStreaming ? "停止推流" : "开始推流"}
        </button>
        
        {error && (
          <div style={{ 
            marginTop: '10px', 
            padding: '8px', 
            backgroundColor: '#f8d7da', 
            color: '#721c24',
            borderRadius: '4px'
          }}>
            {error}
            <button 
              onClick={() => setError(null)} 
              style={{ marginLeft: '10px', padding: '2px 8px', backgroundColor: '#dc3545', color: 'white', border: 'none', borderRadius: '3px' }}
            >
              关闭
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default CameraCapture; 